package cn.gemiman.daoyi.module.netty.server;

import cn.gemiman.daoyi.module.netty.contant.NettyRedisKey;
import jakarta.annotation.PreDestroy;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

@Slf4j
@Component
@AllArgsConstructor
public class NettyServerGroup implements CommandLineRunner {

    public static volatile Long serverId = 0L;

    RedisTemplate<String, Object> redisTemplate;

    private final List<NettyServer> imServers;

    /***
     * 判断服务器是否就绪
     *
     * @return
     **/
    public boolean isReady() {
        for (NettyServer imServer : imServers) {
            if (!imServer.isReady()) {
                return false;
            }
        }
        return true;
    }

    @Override
    public void run(String... args) throws Exception {
        // 初始化SERVER_ID
        String key = NettyRedisKey.IM_MAX_SERVER_ID;
        serverId = redisTemplate.opsForValue().increment(key, 1L);
        // 启动服务
        for (NettyServer imServer : imServers) {
            imServer.start();
        }
    }

    @PreDestroy
    public void destroy() {
        // 停止服务
        for (NettyServer imServer : imServers) {
            imServer.stop();
        }
    }
}
